using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using RawRestructure.Enums;
using RawRestructure.Models;
using RawRestructure.Services.Interfaces;
using System.Text.RegularExpressions;

namespace RawRestructure.Services;

/// <summary>
/// 文件分析服务实现
/// </summary>
public class FileAnalysisService : IFileAnalysisService
{
    private readonly ILogger<FileAnalysisService> _logger;
    private readonly IConfigService _configService;
    private static readonly Regex RawFilePattern = new(@"^([12])_(\d{4})\.raw$", RegexOptions.IgnoreCase | RegexOptions.Compiled);

    public FileAnalysisService(ILogger<FileAnalysisService> logger, IConfigService configService)
    {
        _logger = logger;
        _configService = configService;
    }

    public async Task<ImageInfo> AnalyzeDirectoryAsync(string directoryPath)
    {
        try
        {
            _logger.LogInformation("开始分析目录: {DirectoryPath}", directoryPath);

            if (!Directory.Exists(directoryPath))
            {
                throw new DirectoryNotFoundException($"目录不存在: {directoryPath}");
            }

            // 获取RAW文件列表
            var rawFiles = GetRawImageFiles(directoryPath);
            
            // 统计正位和侧位图像数量
            var paFiles = rawFiles.Where(f => f.IsPA).ToList();
            var latFiles = rawFiles.Where(f => f.IsLAT).ToList();
            
            int paCount = paFiles.Count;
            int latCount = latFiles.Count;

            // 检查是否存在相同序号的正位和侧位图像
            bool hasPairedImages = false;
            
            if (paCount > 0 && latCount > 0)
            {
                // 获取正位图像序号集合
                var paNumbers = paFiles.Select(f => f.ImageNumber).ToHashSet();
                
                // 检查是否有侧位图像与正位图像序号匹配
                hasPairedImages = latFiles.Any(f => paNumbers.Contains(f.ImageNumber));
                
                _logger.LogInformation("检测到相同序号的正位和侧位图像: {HasPairedImages}", hasPairedImages);
            }

            // 确定图像模式
            var imageMode = DetermineImageMode(paCount, latCount, hasPairedImages);
            
            // 计算最小数量
            var minCount = CalculateMinCount(paCount, latCount, imageMode);

            // 检测配置文件
            var configPath = _configService.DetectConfigFile(directoryPath);
            ImageConfig? config = null;
            bool hasConfigFile = false;

            if (!string.IsNullOrEmpty(configPath))
            {
                config = await _configService.ParseConfigFileAsync(configPath);
                hasConfigFile = config != null;
            }

            var result = new ImageInfo
            {
                PaCount = paCount,
                LatCount = latCount,
                MinCount = minCount,
                IsPairMode = hasPairedImages,
                CurrentImageMode = imageMode,
                DirectoryName = Path.GetFileName(directoryPath),
                FullPath = directoryPath,
                HasConfigFile = hasConfigFile,
                Config = config
            };

            _logger.LogInformation("分析完成: PA={PaCount}, LAT={LatCount}, Mode={ImageMode}, IsPairMode={IsPairMode}, HasConfig={HasConfig}", 
                paCount, latCount, imageMode, hasPairedImages, hasConfigFile);

            return result;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "分析目录时发生错误: {DirectoryPath}", directoryPath);
            throw;
        }
    }

    public List<RawImageInfo> GetRawImageFiles(string directoryPath)
    {
        var result = new List<RawImageInfo>();

        try
        {
            var files = Directory.GetFiles(directoryPath, "*.raw", SearchOption.TopDirectoryOnly);
            
            foreach (var filePath in files)
            {
                var fileName = Path.GetFileName(filePath);
                var rawInfo = RawImageInfo.CreateFromFileName(fileName, filePath);
                
                if (rawInfo != null)
                {
                    result.Add(rawInfo);
                }
                else
                {
                    _logger.LogWarning("无效的RAW文件名格式: {FileName}", fileName);
                }
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "扫描RAW文件时发生错误: {DirectoryPath}", directoryPath);
        }

        return result.OrderBy(f => f.ImageType).ThenBy(f => f.ImageNumber).ToList();
    }

    public ImageMode DetermineImageMode(int paCount, int latCount, bool hasPairedImages = false)
    {
        if (paCount > 0 && latCount > 0)
        {
            if (hasPairedImages)
            {
                return ImageMode.PA_LAT_CLEAN; // 正侧位同步清暗场（有相同序号的正位和侧位图像）
            }
            else
            {
                return ImageMode.PA_LAT; // 正侧位交替（没有相同序号的正位和侧位图像）
            }
        }
        else if (paCount > 0)
        {
            return ImageMode.PA; // 仅正位
        }
        else if (latCount > 0)
        {
            return ImageMode.LAT; // 仅侧位
        }
        else
        {
            return ImageMode.PA; // 默认正位
        }
    }

    public int CalculateMinCount(int paCount, int latCount, ImageMode mode)
    {
        return mode switch
        {
            ImageMode.PA => paCount,
            ImageMode.LAT => latCount,
            ImageMode.PA_LAT_CLEAN => Math.Min(paCount, latCount),
            _ => Math.Max(paCount, latCount)
        };
    }
} 